const Koa = require('koa');

const app = new Koa();

const path = require('path');

const query = require('./db/query');

const author = require('./middleware/author.js');

//1.处理静态资源
const static = require('koa-static');

app.use(static(path.join(__dirname,'./public/')));

app.use(author());

//bodyparser 

// const bodyparser = require('koa-bodyparser');

const bodyparser = require('./middleware/bodyparser');

app.use(bodyparser());

// app.use(async (ctx,next) => {})

//2.安装路由功能

const Router = require('koa-router');

const router = new Router();

app.use(router.routes());

app.use(router.allowedMethods());

//3.接口

//新增的接口
router.post('/api/add',async (ctx,next) => {
    let {username,phone,city,address} = ctx.request.body;
    if(username && /\d{11}/.test(phone) && city && address){
        try{
            await query('insert into list (username,phone,city,address) values (?,?,?,?)',[username,phone,city,address]);
            ctx.body = {
                code:1,
                msg:'添加成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})

//修改
router.post('/api/update',async (ctx,next) => {
    let {username,phone,city,address,id} = ctx.request.body;
    if(username && /\d{11}/.test(phone) && city && address && id){
        try{
            await query('update list set username=?,phone=?,city=?,address=? where id=?',[username,phone,city,address,id]);
            ctx.body = {
                code:1,
                msg:'修改成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})

//查询
router.get('/api/list',async (ctx,next) => {
    //查看第几页的数据  pagenum  每页的条数  limit  总条数 total
    let {pagenum=1,limit=2} = ctx.query;

    let startIndex = (pagenum-1)*limit;
    let list = await query(`select * from list limit ${startIndex},${limit}`);
    let total = await query('select count(*) from list');
    console.log(total);
    ctx.body = {
        code:1,
        data:list,
        total:total[0]['count(*)']
    }
})

router.delete('/api/del',async (ctx,next) => {
    let {id} = ctx.query;
    if(id){
        try{
            await query('delete from list where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }    
    }
})

router.get('/test',async (ctx) => {
    ctx.body = '123'
})

app.listen(3000,() => {
    console.log("服务启动成功")
})